﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Speech.Synthesis;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using AForgeTest;
using ArcSoftFace.SDKModels;
using ArcSoftFace.SDKUtil;
using ArcSoftFace.Utils;
using IntelligentPharmacy.Entity;
using IntelligentPharmacy.httprequest;
using IntelligentPharmacy.publicclass;
using Reader;
using SmartForcer;
using SmartForcer.Enum;
using SmartRoom;
using SourceAFIS.Simple;
using System.Windows.Threading;

namespace ConsumablesCabinet
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        requestService request = new requestService();

        /// <summary>
        /// 标识是否有一个登录成功 
        /// </summary>
        private volatile bool isRegister = true;
        /// <summary>
        /// 显示日期的
        /// </summary>
        private DispatcherTimer ShowTimer;

        SpeechSynthesizer synth = new SpeechSynthesizer();
        /// <summary>
        /// 播放声音
        /// </summary>
        /// <param name="dwFreg"></param>
        /// <param name="dwDuration"></param>
        /// <returns></returns>
        [DllImport("kernel32")]
        public static extern int Beep(int dwFreg, int dwDuration);

        #region 指纹
        private Thread CollectionThread = null;

        private static System.Timers.Timer _startTimer;
        private IntPtr DeviceHandle = IntPtr.Zero;
        private UInt32 N_ADDR = 0XFFFFFFFF;//设备地址
        bool IsCollection = false;
        static AfisEngine AFIS = new AfisEngine();
        List<UserFingerBit> _userFingerList = new List<UserFingerBit>();
        #endregion
        private Boolean isConnect = false;
        private volatile Boolean isUserLogin = false;
        
        public MainWindow()
        {
            InitializeComponent();
            AForgeTest.CameraHelper.IsDisplay = true;
            AForgeTest.CameraHelper.SourcePlayer = player;
            AForgeTest.CameraHelper.UpdateCameraDevices();

            this.PictureOfGifss.ImageLocation = AppDomain.CurrentDomain.BaseDirectory + "\\Resources\\images\\FingerScan.gif";
            if (!Global.LoadConfig())
            {
                MessageBox.Show("读取配置文件失败请重新启动电脑");
            }
            loadFingerprintMessage();

            ShowTimer = new System.Windows.Threading.DispatcherTimer();
            ShowTimer.Tick += new EventHandler(ShowCurTimer);//起个Timer一直获取当前时间
            ShowTimer.Interval = new TimeSpan(0, 0,0, 1, 0);
            ShowTimer.Start();
            ThreadPool.SetMinThreads(1, 1);
            ThreadPool.SetMaxThreads(4, 4);
            try
            {
                Dictionary<string, string> dic = new Dictionary<string, string>();
                List<TagEntity> listTag = request.getStockList();
                foreach (TagEntity tag in listTag)
                {
                    dic.Add(tag.rfid, "");
                }
                Global.AfterRfidList = dic;
            }
            catch (Exception e1)
            {
                Global.MessageWindow.ShowDialog("下载库存失败");
            }
        }
        public void ShowCurTimer(object sender, EventArgs e)
        {
            //获得时分秒
            this.time.Content = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

        }
        /// <summary>
        /// 判断登录那个界面
        ///  <!--配登录界面 大门口的是1，管理员2，护士3-->
        /// </summary>
        private void ifInterface()
        {

            if (!isRegister)
                return;
            isRegister = false;
            Dispatcher.BeginInvoke(new Action(delegate
            {
                MenuWindows menuWindows = new MenuWindows();
                Global.WindowsList.Add(menuWindows);
                menuWindows.ShowDialog();
                Global.WindowsList.Remove(menuWindows);

                isRegister = true;
                Global.User = null;
                click_frame.Visibility = Visibility.Visible;
                Paybycard.Visibility = Visibility.Hidden;
                mFace.Visibility = Visibility.Hidden;
                FingerPrint.Visibility = Visibility.Hidden;
            }));
        }

        /// <summary>
        /// 加载指纹信息
        /// </summary>
        private void loadFingerprintMessage()
        {
            WaitWindow wait = new WaitWindow("正在下载指纹信息，请稍等...");
            try
            {//库房id
                request.getUserMessage("");

                foreach (UserFace obj in Global.listuserFace)
                {
                    if (obj.fpData == null || obj.fpData == "" || obj.fpData.Length < 20)
                        continue;
                    //获取数据库中的指纹信息
                    byte[] bytes = Convert.FromBase64String(obj.fpData);
                    Bitmap bit1 = ShowFingerPrint(bytes);
                    //数据库中的的指纹信息
                    Fingerprint fp = new Fingerprint();
                    Person dataPerson = new Person(fp);
                    fp.AsBitmap = bit1;
                    AFIS.Extract(dataPerson);
                    UserFingerBit fBit = new UserFingerBit();
                    fBit.UserID = obj.empId;
                    fBit.QueryData = dataPerson;
                    _userFingerList.Add(fBit);
                }
            }
            catch (Exception ex)
            { }
            wait.Close();
            OpenCollection();
        }
        /// <summary>
        /// 打开指纹
        /// </summary>
        private void OpenCollection()
        {
            try
            {
                int result = DriveOpration.PSOpenDeviceEx(ref DeviceHandle, DriveOpration.DEVICE_UDisk, DriveOpration.COM1, DriveOpration.BAUD_RATE_57600, 2, 0);
                if (DeviceHandle == IntPtr.Zero || result != 0)
                {
                    Global.MessageWindow.ShowDialog("打开指纹设备失败！", MessageButton.Close, MessageStyle.Error);
                }
                else
                {
                    CollectionThread = new Thread(new ThreadStart(FigerCollection));
                    CollectionThread.Start();
                }
            }
            catch (Exception ex)
            {
                Global.MessageWindow.ShowDialog("打开指纹设备失败！", MessageButton.Close, MessageStyle.Error);
                StopCollection();
            }
        }
        /// <summary>
        /// 关闭指纹
        /// </summary>
        private void StopCollection()
        {
            try
            {
                IsCollection = true;
                DriveOpration.PSCloseDeviceEx(DeviceHandle);

                if (CollectionThread != null && CollectionThread.IsAlive)
                {
                    CollectionThread.Abort();
                }
            }
            catch (Exception ex)
            {
            }
        }
        public Bitmap ShowFingerPrint(byte[] rgbValues)
        {
            Bitmap bmp = new Bitmap(256, 288);//指纹图片
            for (int i = 0; i < bmp.Height; i++)
            {
                for (int j = 0; j < bmp.Width; j++)
                {
                    int value = (int)rgbValues[i * bmp.Width + j];
                    System.Drawing.Color c = System.Drawing.Color.FromArgb(value, value, value);

                    bmp.SetPixel(j, i, c);
                }
            }
            return bmp;
        }
        private void CheckFinger(byte[] byt)
        {
            try
            {
                Logger.WriteLog("开始验证" + DateTime.Now);
                //采集到的指纹信息
                Fingerprint fpSource = new Fingerprint();
                Person queryPerson = new Person(fpSource);
                fpSource.AsBitmap = ShowFingerPrint(byt);
                AFIS.Extract(queryPerson);
                Logger.WriteLog("准备完成" + DateTime.Now);

                bool isCheck = false;

                foreach (UserFingerBit obj in _userFingerList)
                {
                    float verify = AFIS.Verify(queryPerson, obj.QueryData);
                    if (verify >= Global.FingerCheckValue)//验证通过
                    {
                        Logger.WriteLog("指纹识别值" +DateTime.Now+"----"+ verify);
                        //验证通过之后进行库房
                        foreach (UserFace item in Global.listuserFace)
                        {
                            if (item.empId == obj.UserID)
                            {
                                Global.User = item;
                            }
                        }
                         isCheck = true;
                       // Beep(3000, 100);
                         ifInterface();
                         IsCollection = false;
                        break;
                    }
                }
                if (!isCheck)
                {
                    try
                    {
                        // synth.Speak("请重新输入指纹");
                    }
                    catch
                    {
                        Beep(3000, 50);
                        Beep(3000, 50);
                    }
                }
                IsCollection = false;
            }
            catch (Exception ex)
            {
                Global.MessageWindow.ShowDialog(ex.Message, MessageButton.Close, MessageStyle.Warn);
            }
            finally
            {

            }
        }

        private void FigerCollection()
        {
            try
            {
                while (!IsCollection)
                {

                    int ret = -1;
                    do
                    {
                        ret = DriveOpration.PSGetImage(DeviceHandle, N_ADDR);
                    }
                    while (ret != DriveOpration.PS_OK);

                    if (ret == DriveOpration.PS_OK)
                    {
                        UInt16 templateLength = 0;
                        byte[] imageData = new byte[256 * 288];

                        ret = DriveOpration.PSUpImage(DeviceHandle, 1, imageData, ref templateLength);//上传图片
                        if (ret == DriveOpration.PS_OK)
                        {
                            CheckFinger(imageData);
                        }
                    }
                }
            }
            catch (Exception ex)
            { }
        }
        /// <summary>
        /// 刷卡识别
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Grid_MouseDown(object sender, MouseButtonEventArgs e)
        {
            click_frame.Visibility = Visibility.Hidden;
            Paybycard.Visibility = Visibility.Visible;
        }
        /// <summary>
        /// 指纹识别
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void Image_MouseDown(object sender, MouseButtonEventArgs e)
        {
            //synth.Speak("指纹开始识别中");
            //click_frame.Visibility = Visibility.Hidden;
            //FingerPrint.Visibility = Visibility.Visible;
        }
        /// <summary>
        /// 退出指纹识别切换到大页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void exit_Finger_Click(object sender, RoutedEventArgs e)
        {
            click_frame.Visibility = Visibility.Visible;
            FingerPrint.Visibility = Visibility.Hidden;
        }
        /// <summary>
        /// 人脸识别
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Image_MouseDown_1(object sender, MouseButtonEventArgs e)
        {
            ShowTimer.Stop();
            click_frame.Visibility = Visibility.Hidden;
            mFace.Visibility = Visibility.Visible;
        }
        private void closemFace_Click(object sender, RoutedEventArgs e)
        {
            ShowTimer.Start();
            click_frame.Visibility = Visibility.Visible;
            mFace.Visibility = Visibility.Hidden;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            /*NurseMenuWindow menuWindows = new NurseMenuWindow();
            GlobalAttribute.WindowsList.Add(menuWindows);
            menuWindows.ShowDialog();
            GlobalAttribute.WindowsList.Remove(menuWindows);*/
        }
        /// <summary>
        /// 登录 GAdmin  
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            string namem = name.Text.Trim();
            string passWord = password.Password.Trim();
            if (request.register(namem, passWord))
            {
                ifInterface();
            }
            else
            {
                Global.MessageWindow.ShowDialog("登录失败请输入正确的账号或者密码", MessageButton.Close, MessageStyle.Warn);
            }
            name.Text = null;
            password.Password = null;
        }
        /// <summary>
        /// 退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            click_frame.Visibility = Visibility.Visible;
            Paybycard.Visibility = Visibility.Hidden;
        }
        /// <summary>
        /// 获取摄像头的每一帧
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private volatile bool isLock = true;
        ASF_SingleFaceInfo singleFaceInfo = new ASF_SingleFaceInfo();
        private void player_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
        {
            try
            {
                if (isLock == true)
                {
                    isLock = false;
                    if (CameraHelper.getvideo().IsRunning)
                    {
                        //string TheLock = "" + wfh_Scan.Visibility;
                        if (!isUserLogin)
                        {
                            ThreadPool.QueueUserWorkItem(new WaitCallback(delegate
                            {
                               /* Dispatcher.BeginInvoke(new Action(delegate
                                {
                                   
                                }));*/
                                Bitmap bitmap1 = CameraHelper.getCurrentVideo();
                                ASF_MultiFaceInfo multiFaceInfo = FaceUtil.DetectFace(Engine.pImageEngine, bitmap1);
                                if (multiFaceInfo.faceNum >= 1)
                                {
                                    IntPtr feature = FaceUtil.ExtractFeature(Engine.pImageEngine, bitmap1, out singleFaceInfo);
                                    if (Global.listuserFace.Count <= 0)
                                    {//库房id
                                        request.getUserMessage("");
                                    }
                                    for (int i = 0; i < Global.listuserFace.Count; i++)
                                    {
                                        float similarity = 0f;
                                        //Convert.FromBase64String(obj.fpDate)
                                        ASFFunctions.ASFFaceFeatureCompare(Engine.pImageEngine, Engine.PutFeatureByteIntoFeatureIntPtr
                                            (Convert.FromBase64String(Global.listuserFace[i].faceData)), feature, ref similarity);
                                        // Global.MessageWindow.ShowDialog("相识度" + similarity, Enum.MessageButton.Close, Enum.MessageStyle.Error);
                                        if (similarity.ToString().IndexOf("E") > -1)
                                        {
                                            similarity = 0f;
                                        }
                                        if (similarity > 0.8)
                                        {
                                            Global.User = Global.listuserFace[i];
                                            /*MenuWindows menu = new MenuWindows();
                                            menu.ShowDialog();*/
                                            ifInterface();
                                            Thread.Sleep(3000);
                                            isLock = true;
                                            return;
                                        }
                                    }
                                }
                                else
                                {
                                    isLock = true;
                                }
                                isLock = true;
                            }));
                        }
                    }
                    else
                    {
                        CameraHelper.getvideo();
                        isLock = true;
                    }
                }
            }
            catch (Exception ex)
            {
                Global.MessageWindow.ShowDialog(ex.Message, MessageButton.Close, MessageStyle.Warn);
            }
        }
        /// <summary>
        /// 召唤小键盘
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Label_MouseDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                Process.Start(@"C:\Program Files\Common Files\Microsoft Shared\Ink\TabTip.exe");
            }
            catch
            {
                try
                {
                    Process.Start(Environment.CurrentDirectory + "\\Asset\\exe\\keyboard.exe");
                }
                catch
                { }
            }
        }
    }
    public class UserFingerBit
    {
        private string _userID;
        private Person _queryData;
        public string UserID { get => _userID; set => _userID = value; }
        public Person QueryData { get => _queryData; set => _queryData = value; }
    }
}